var {
  randomUtils,
  textUtils,
  timeUtils,
  clickUtils,
  ocrUtils,
  logUtils,
} = require ('../../utils/index');
var adCommon = require ('../adCommon');
module.exports = {
  watchAd (span, handleNextAd) {
    this.span = span;
    this.handleNextAd = handleNextAd;
    var startTime = Date.now ();
    var count = 0;
    adCommon.adCount++;
    logUtils.info ('第', adCommon.adCount, '/', adCommon.maxAdCount, '个广告');
    while (true) {
      count++;
      var hasExec = timeUtils.hasExec (startTime);
      if (count % 5 == 0) {
        logUtils.info ('已经观看', hasExec, '/', this.span);
      }
      if (count >= 4 && this.isOver ()) {
        this.stopAd ();
        break;
      }
      if (hasExec >= 30) {
        logUtils.info ('已经看广告25s，开始检测是否在广告页面');
        if (!this.checkInAd ()) {
          back ();
          sleep (randomUtils.getRandom (3, 4, 1000));
          this.span = this.span + 10;
        }
      }
      if (hasExec > this.span) {
        if (count % 5 != 0) {
          logUtils.info ('已经观看', hasExec, '/', this.span, '将执行关闭广告');
        }
        this.stopAd ();
        break;
      }
      sleep (2 * 1000);
    }
  },
  stopAd () {
    for (var index = 0; index < 2; index++) {
      back ();
      sleep (randomUtils.getRandom (1.5, 2, 1000));
      var exitContents = [
        //prettier-disable
        '坚持退出',
      ];
      var hasNextContents = [
        //prettier-disable
        '领取奖励',
      ];
      if (adCommon.adCount >= adCommon.maxAdCount) {
        var TextUI = textUtils.existsOneTextStartsWith (exitContents);
        if (TextUI) {
          clickUtils.clickTextUI (TextUI);
          sleep (randomUtils.getRandom (1.5, 2, 1000));
          return;
        }
      } else {
        var TextUI = textUtils.existsOneTextStartsWith (hasNextContents);
        if (TextUI) {
          clickUtils.clickTextUI (TextUI);
          sleep (randomUtils.getRandom (1.5, 2, 1000));
          this.handleNextAd && this.handleNextAd ();
          return;
        }
      }
      if (!this.inAd ()) {
        logUtils.info ('没有广告，退出');
        return;
      }
    }
  },
  checkInAd () {
    return this.inAd ();
  },
  inAd () {
    var contents = [
      //prettier-disable
      '广告',
      '反馈',
    ];
    var TextUI = textUtils.existsOneTextStartsWith (contents);
    if (TextUI) {
      return TextUI;
    }
    var TextOCR = ocrUtils.captureExistsOneText (contents);
    if (TextOCR) {
      return TextOCR;
    }
    return false;
  },
  isOver () {
    var contents = [
      //prettier-disable
      '领取成功',
    ];
    var TextOCR = ocrUtils.captureExistsOneText (contents);
    if (TextOCR) {
      return TextOCR;
    }
    return false;
  },
};
